package com.tony.mindweather.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.tony.mindweather.config.SayLoveConfig;
import com.tony.mindweather.entity.*;
import com.zjiecode.wxpusher.client.WxPusher;
import com.zjiecode.wxpusher.client.bean.Message;
import com.zjiecode.wxpusher.client.bean.MessageResult;
import com.zjiecode.wxpusher.client.bean.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Classname WeatherWithSayLoveController
 * @Description TODO
 * @Date 2022/1/27 23:20
 * @Created by
 */
@Controller
public class WeatherWithSayLoveController {
    /**
     * 邮箱号
     */
    @Value("${spring.mail.username}")
    private String email;

    @Value("${sayloveurlAPIKEY}")
    private String sayloveurl;

    @Value("${city}")
    private String city;

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SayLoveConfig sayLoveConfig;

    @Value("${weChatMessageToken}")
    private String weChatMessageToken;

    @Value("${TonyWeChatID}")
    private String TonyWeChatID;


    private int loveday = 2;//相爱天数

    /*
     * 异步处理还是非常常用的，比如我们在网站上发送邮件，后台会去发送邮件，此时前台会造成响应不动，直到邮件发送完毕，响应才会成功，
     * 所以我们一般会采用多线程的方式去处理这些任务。
     *
     * 解决方案：
     *   给方法添加@Async注解
     *   SpringBoot就会自己开一个线程池，进行调用！但是要让这个注解生效，我们还需要在主程序上添加一个注解@EnableAsync ，开启异步注解功能；
     * */
    @GetMapping("/process")
    public void process() {
        SimpleMailMessage message = new SimpleMailMessage();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日E");
        String datestr = sdf.format(new Date());
        message.setSubject(datestr + "上海的天气");//主题

        /*天气API*/
        String apiURL = "http://wthrcdn.etouch.cn/weather_mini?city=" + "上海";
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(apiURL, String.class);// 发起天气请求
        ObjectMapper objectMapper = new ObjectMapper();
        WeatherResponse resp = null;
        String strBody = null;
        if (responseEntity.getStatusCodeValue() == 200) {
            strBody = responseEntity.getBody();
        }
        try {
            resp = objectMapper.readValue(strBody, WeatherResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        final Weather data = resp.getData();
        final String weathercity = data.getCity();
        final String ganmao = data.getGanmao();
        final String wendu = data.getWendu();
        final Forecast forecast = data.getForecast().get(0);
        final String high = forecast.getHigh();
        final String low = forecast.getLow();
        final String type = forecast.getType();
        String showWeather =  weathercity+type + ",最" + high + ",最" + low + ",当前温度" + wendu + "。";

        // 处理土味情话
        String sayLoveAPIURL = "http://api.tianapi.com/saylove/index?key=" + sayloveurl;
        final String sayLoveString = sayLoveConfig.SayLoveRequest(sayLoveAPIURL);
        final String[] split = sayLoveString.split("\":\"");
        final String SayLoveContent = split[split.length - 1].split("\"")[0];

        /*要发送的内容*/
        String showWeatherWithSayLove = "早安呀,小宝贝，今天是小猪爱你的第" + loveday + "天。\n" +
                "下面由小猪为小宝贝播报" + weathercity + "的天气：" + showWeather + "\r\n今日情话：" + SayLoveContent + "——爱你的小猪！";

        /*发送微信*/
        Message weChatMessage = new Message();
        weChatMessage.setAppToken(weChatMessageToken);
        weChatMessage.setContentType(Message.CONTENT_TYPE_TEXT);
        weChatMessage.setContent(showWeatherWithSayLove);
        weChatMessage.setUid(TonyWeChatID); // 发给个人
        // weChatMessage.setUid(SheepWeChatID);
        // final Set<String> uids = new HashSet<>();
        // uids.add(TonyWeChatID);
        // uids.add(SheepWeChatID);
        // weChatMessage.setUids(uids); // 发给uid 集合
        Result<List<MessageResult>> result = WxPusher.send(weChatMessage);

        loveday = loveday + 1;
        /*邮件处理模块2*/
        message.setText(showWeatherWithSayLove); // 内容
        message.setTo("1360844239@qq.com"); // 接收者
        message.setFrom("1360844239@qq.com"); // 发送者

        mailSender.send(message);


    }
}
